//
//  LPCalendarView.m
//  Calendar
//
//  Created by yiqiang on 16/7/12.
//  Copyright © 2016年 yiqiang. All rights reserved.
//

#import "YACalendarView.h"
#import "DayButton.h"

@interface YACalendarView()

@property (nonatomic,strong)DayButton  *selectButton;
@property (nonatomic,strong)RequestSession *photoNumberRequest;
@property (nonatomic,strong)NSMutableDictionary *monthDict;
@end

@implementation YACalendarView
{
    NSMutableArray *_daysArray;
    
    UILabel *headlabel;
    
    UIButton *rightButton;
    UIImageView *rightImg;
    
    NSDate *selectedDate;
}


/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _daysArray = [NSMutableArray arrayWithCapacity:42];
        for (int i = 0; i < 42; i++) {
            
            DayButton *button = [[DayButton alloc] initWithFrame:CGRectZero];
            [button addTarget:self action:@selector(selectDateAction:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:button];
            [_daysArray addObject:button];
            
        }
        [self createCalendarViewWith:[NSDate date]];
        
    }
    return self;
}

- (void)selectDateAction:(DayButton *)sender {
    if (sender != _selectButton) {
        selectedDate = [YACalendarDate dateWithYear:[YACalendarDate year:selectedDate] month:[YACalendarDate month:selectedDate] day:[sender.titleLabel.text integerValue]];
        [sender setDayButtonType:DayButtonTypeSelected];
        [_selectButton setDayButtonType:DayButtonTypeNormal];
        _selectButton = sender;
        headlabel.text = [YACalendarDate formatterString:@"yyyy-MM-dd" Date:selectedDate];
        [self sendDelegateWithPhotoNumber:sender.photoNumber];
        NSLog(@"zz%@",sender.titleLabel.text);
    }
  
}

#pragma mark - create View



- (void)createCalendarViewWith:(NSDate *)date{
    
    selectedDate=date;
    
    CGFloat itemW     = self.frame.size.width / 7;
    CGFloat itemH     = self.frame.size.height / 8;
    
    // 1.year month
    headlabel = [[UILabel alloc] init];
    headlabel.textColor = RGB16(0x333333);
    headlabel.text = [YACalendarDate formatterString:@"yyyy-MM-dd" Date:selectedDate];
    headlabel.font     = [UIFont systemFontOfSize:14];
    headlabel.frame           = CGRectMake( self.frame.size.width/2-50, 0, 100, itemH);
    headlabel.textAlignment   = NSTextAlignmentCenter;
    [self addSubview:headlabel];
    
    //last month
    UIButton *leftButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    leftButton.frame=CGRectMake(headlabel.frame.origin.x-100, 0, 40, itemH);
    [leftButton addTarget:self action:@selector(clickMonth:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:leftButton];
    
    UIImageView *leftImg=[[UIImageView alloc] initWithFrame:CGRectMake(leftButton.frame.size.width-10, (leftButton.frame.size.height-15)/2, 10, 15)];
    leftImg.image=[UIImage imageNamed:@"leftarr.png"];
    [leftButton addSubview:leftImg];
    
    //next month   if greater than the current month does not show
    rightButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    rightButton.frame=CGRectMake(CGRectGetMaxX(headlabel.frame)+100-itemH, leftButton.frame.origin.y, leftButton.frame.size.width, leftButton.frame.size.height);
    [rightButton addTarget:self action:@selector(clickMonth:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:rightButton];
    
    rightImg=[[UIImageView alloc] initWithFrame:CGRectMake(0, (rightButton.frame.size.height-15)/2, 10, 15)];
    rightImg.image=[UIImage imageNamed:@"rightarr"];
    [rightButton addSubview:rightImg];
    
    // 2.weekday
    NSArray *array = @[@"日", @"一", @"二", @"三", @"四", @"五", @"六"];
    UIView *weekBg = [[UIView alloc] init];
    weekBg.frame = CGRectMake(0, CGRectGetMaxY(headlabel.frame), self.frame.size.width, itemH-10);
    [self addSubview:weekBg];
    
    for (int i = 0; i < 7; i++) {
        UILabel *week = [[UILabel alloc] init];
        week.text     = array[i];
        week.font     = [UIFont systemFontOfSize:14];
        week.frame    = CGRectMake(itemW * i, 0, itemW, 32);
        week.textAlignment   = NSTextAlignmentCenter;
        week.backgroundColor = [UIColor clearColor];
        week.textColor       = RGB16(0x999999);
        [weekBg addSubview:week];
    }
    
//    NSInteger daysInLastMonth = [YACalendarDate totaldaysInMonth:[YACalendarDate lastMonth:date]];
//    NSInteger daysInThisMonth = [YACalendarDate totaldaysInMonth:date];
//    NSInteger firstWeekday    = [YACalendarDate firstWeekdayInThisMonth:date];
    //  3.days (1-31)
    for (int i = 0; i < 42; i++) {
        
        int x = (i % 7) * itemW ;
        int y = (i / 7) * itemH + CGRectGetMaxY(weekBg.frame);
        
        DayButton *dayButton = _daysArray[i];
        
        dayButton.frame = CGRectMake(x, y, itemW, itemH);
//        NSInteger day = 0;
//
//        if (i < firstWeekday) {
//            day = daysInLastMonth - firstWeekday + i + 1;
//            [dayButton setDayButtonType:DayButtonTypeInvalid];
//
//        }else if (i > firstWeekday + daysInThisMonth - 1){
//            day = i + 1 - firstWeekday - daysInThisMonth;
//            [dayButton setDayButtonType:DayButtonTypeInvalid];;
//
//        }else{
//            day = i - firstWeekday + 1;
//            [dayButton setDayButtonType:DayButtonTypeNormal];
//        }
//
//        [dayButton setTitle:[NSString stringWithFormat:@"%li", day] forState:UIControlStateNormal];
//        dayButton.tag = day;
//        // this month
//        NSInteger todayIndex = [YACalendarDate day:[NSDate date]] + firstWeekday - 1;
//
//        if([self judgementMonth] && i ==  todayIndex)
//        {
//            [dayButton setDayButtonType:DayButtonTypeSelected];
////            _dayButton = dayButton;
//            _selectButton = dayButton;
//        }else
//        {
//            dayButton.backgroundColor=[UIColor whiteColor];
//        }
    }
    [self reloadDayButtons];
    [self requestPhotoNumberWithMonth:[YACalendarDate formatterString:@"yyyyMM" Date:selectedDate]];
}


#pragma mark - date button style
- (void)reloadDayButtons {
    NSDate *date=selectedDate;
    
    headlabel.text = [YACalendarDate formatterString:@"yyyy-MM-dd" Date:selectedDate];
    
    NSInteger daysInLastMonth = [YACalendarDate totaldaysInMonth:[YACalendarDate lastMonth:date]];
    NSInteger daysInThisMonth = [YACalendarDate totaldaysInMonth:date];
    NSInteger firstWeekday    = [YACalendarDate firstWeekdayInThisMonth:date];
    
    //    NSInteger todayIndex = [YACalendarDate day:[NSDate date]] + firstWeekday - 1;
    NSInteger selectIndex =  [YACalendarDate day:date] + firstWeekday - 1;
    
    for (int i = 0; i < 42; i++) {
        
        DayButton *dayButton = _daysArray[i];
        //每次切换月份的时候，重置所以按钮的蓝点
        dayButton.photoNumber = 0;
        NSInteger day = 0;
        
        if (i < firstWeekday) {
            day = daysInLastMonth - firstWeekday + i + 1;
            [dayButton setDayButtonType:DayButtonTypeInvalid];
            [dayButton setTitle:nil forState:UIControlStateNormal];
            dayButton.tag = 0;
            
        }else if (i > firstWeekday + daysInThisMonth - 1){
            day = i + 1 - firstWeekday - daysInThisMonth;
            [dayButton setDayButtonType:DayButtonTypeInvalid];
            [dayButton setTitle:nil forState:UIControlStateNormal];
            dayButton.tag = 0;
        }else{
            day = i - firstWeekday + 1;
            [dayButton setDayButtonType:DayButtonTypeNormal];
            [dayButton setTitle:[NSString stringWithFormat:@"%li", day] forState:UIControlStateNormal];
            dayButton.tag = day;
        }
        if (i == selectIndex) {
            [dayButton setDayButtonType:DayButtonTypeSelected];
            _selectButton = dayButton;
        }
    }
}

-(BOOL) judgementMonth
{
    //获取当前月份
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    formatter.dateFormat=@"MM";
    NSInteger dateMon=[[formatter stringFromDate:[NSDate date]] integerValue];
    
    //获取选择的月份
    NSInteger mon=[[headlabel.text substringFromIndex:5] integerValue];
    
    if (mon==dateMon)
    {
        return YES;
    }else
        return NO;
}


-(void) clickMonth:(UIButton *)btn
{
    if (btn==rightButton)
    {
        selectedDate=[YACalendarDate nextMonth:selectedDate];
    }else
    {
        selectedDate=[YACalendarDate lastMonth:selectedDate];
    }
    [self reloadDayButtons];
    [self reloadPhotoNumberOnButton];
    [self requestPhotoNumberWithMonth:[YACalendarDate formatterString:@"yyyyMM" Date:selectedDate]];

}

#pragma mark - Request

- (void)reloadPhotoNumberOnButton {
    NSString *monthKey = [YACalendarDate formatterString:@"yyyyMM" Date:selectedDate];
    NSDictionary *monthDict = [self.monthDict objectForKey:monthKey];
    if (monthDict != nil) {
        for (DayButton *btn in _daysArray) {
            if (btn.tag != 0) {
                NSString *key = [NSString stringWithFormat:@"%li",btn.tag];
                if ([monthDict objectForKey:key]) {
                    NSInteger number = [monthDict tm_integerForKey:key];
                    btn.photoNumber = number;
                }else {
                    btn.photoNumber = 0;
                }
            }else {
                btn.photoNumber = 0;
            }
        }
    }
    [self sendDelegateWithPhotoNumber:self.selectButton.photoNumber];
}

- (void)sendDelegateWithPhotoNumber:(NSInteger )number {
    NSDate *date = selectedDate;
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectNewDay:photoNumber:calendarView:)]) {
        [self.delegate selectNewDay:date photoNumber:number calendarView:self];
    }
}

- (void)requestPhotoNumberWithMonth:(NSString *)month {
    NSString *urlStr = WO_PATH_PHOTO_NUMBER_MONTH;
    NSDictionary *params = @{
                             @"time":month,
                             };
    @weakify(self);
    [self.photoNumberRequest postWithURLString:WO_URL(urlStr) parameters:params completionHandler:^(id responseObject, NSError *error) {
        @strongify(self);
        if (!error ) {
            NSDictionary *data = [responseObject tm_dictionaryForKey:@"data"];
            NSArray *listArray = [data tm_arrayForKey:@"dateListVOList"];
            NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
            for (NSDictionary *dict in listArray) {
                NSString *key = [NSString stringWithFormat:@"%@",dict[@"date"]];
                NSString *value = [NSString stringWithFormat:@"%@",dict[@"count"]];
                [mutableDict setObject:value forKey:key];
            }
            [self.monthDict setObject:mutableDict forKey:month];
            
        }else {
            
        }
        [self reloadPhotoNumberOnButton];
    }];
}

- (RequestSession *)photoNumberRequest {
    if (!_photoNumberRequest) {
        _photoNumberRequest = [[RequestSession alloc] init];
    }
    return _photoNumberRequest;
}

- (NSMutableDictionary *)monthDict {
    if (!_monthDict) {
        _monthDict = [NSMutableDictionary dictionary];
    }
    return _monthDict;
}


@end
